import Router from '@koa/router';
import sequelize from '../config/db.js';
const router = new Router({ prefix: '/api' });


// 统一的错误响应结构
const errorResponse = (code, message) => ({
  code,
  message,
  data: null
});

// 统一的成功响应结构
const successResponse = (data, meta = null) => ({
  code: 'SUCCESS',
  message: '操作成功',
  data,
  meta
});

// 获取总访问人数的接口
router.get('/visits', async (ctx) => {
  try {
    // 获取当前登录用户信息（假设用户信息存储在 ctx.state.user 中）
    // 查询文章总数
    const [articleResult] = await sequelize.query(`
      SELECT COUNT(*) AS articleTotal 
      FROM wp_blog_posts 
      WHERE post_type = 'post' AND post_status = 'publish'
    `);
    // 查询分类总数
    const [categoryResult] = await sequelize.query(`
      SELECT COUNT(*) AS categoryTotal 
      FROM wp_blog_term_taxonomy 
      WHERE taxonomy = 'category'
      `);

    const [visitResult] = await sequelize.query('SELECT COUNT(*) AS visitTotal FROM visits')
    const { articleTotal } = articleResult[0]
    const { categoryTotal } = categoryResult[0];
    const { visitTotal } = visitResult[0]


    // 返回结果
    ctx.body = {
      code: 'SUCCESS',
      data: {
        articleTotal, // 文章总数
        categoryTotal, // 分类总数
        visitTotal, // 访问量
      },
    };
  } catch (error) {
    ctx.status = 500;
    ctx.body = {
      code: 'ERROR',
      message: '获取数据失败',
      error: error.message,
    };
  }
});

export default router;